<?php
namespace app\admin\controller;
use think\Db;
use think\Controller;
use think\facade\Request;
use think\Validate;
use app\admin\model\Section as SectionModel;
class Section extends Common
{
    /**部门列表
     * URL：admin/section/lists
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function lists(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));
            $section_id=input('id');
            if($section_id!=''){
                $section = new Section();
                $str = $section_id;
                foreach ($section->showCate($section_id) as $k=>$v){
                    $str .= ",".$v['section_id'];
                }
                $list = Db::name('section')->alias('s')
                    ->join('teacher t','t.section_id=s.section_id')
                    ->where('s.is_del',0)
                    ->where('t.is_del',0)
                    ->where('t.section_id','in',$str)
                    ->where('s.title', 'like', "%" . $keyword . "%")
                    ->order('s.create_time desc')
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();
            }else{
                $list = Db::name('section')->alias('s')
                    ->join('teacher t','t.section_id=s.section_id')
                    ->where('s.is_del',0)
                    ->where('t.is_del',0)
                    ->where('s.title', 'like', "%" . $keyword . "%")
                    ->order('s.create_time desc')
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();
            }

            if (! empty($list)) {
                foreach ($list['data'] as $k => $v) {

                    $list['data'][$k]['create_time'] = toDate($v['create_time']);
                    $list['data'][$k]['update_time'] = toDate($v['update_time']);
                }
            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        else{
            $section_list = $this->getCate();
            $this->assign('section_list',$section_list);
        }

        return $this->fetch('section_list');
    }

    /**无限极分类
     * @param int $pid
     * @param array $result
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCate($pid=0,&$result=[]){
        $res = Db::name('section')->where('pid',$pid)->select();
        foreach ($res as $k=>$v){
            $result[] =$v;
            self::getCate($v['section_id'],$result);
        }
        return $result;
    }

    /**拿到子菜单数据
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function show_child(){
        $res = Db::name('section')->where('pid',input('section_id'))->where('is_del',0)->select();
        return $res;

    }

    /**
     * *****************************************************************************************************************
     */

    /**部门展示
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function manage(){

        if (request()->isAjax()) {


            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));
            $list = $this->showCate();
            $max = $pageSize*$page;
            $min = $max - $pageSize;

            $temp = [];

            if (!empty($list)) {

                foreach ($list as $k=>$v){

                    if($k<$max&&$k>=$min){
                        $list[$k]['create_time'] = toDate($v['create_time']);
                        $list[$k]['update_time'] = toDate($v['update_time']);
                        $temp[] = $v;
                    }

                }
            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$temp,'count'=>count($list),'rel'=>1];
        }

        return $this->fetch('manage');



    }

    /**
     * 无限极分类数据获取
     * @param int $pid
     * @param array $result
     * @param int $blank
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function showCate($pid=0,&$result=[],$blank=-1){

        $res = Db::name('section')
            ->where('is_del',0)
            ->where('pid',$pid)
            ->select();

        $blank += 1;

        foreach ($res as $k=>$v){

            $v['title'] = str_repeat('|—',$blank).$v['title'];

            $result[] =$v;

            $this->showCate($v['section_id'],$result,$blank);

        }

        return $result;

    }

    /**
     * 部门添加
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function addSection(){

        if (request()->isAjax()) {

            $data = input('post.');
            $user = Db::name('section')->where(['title'=>$data['title']])->find();
            if($user){
                $this->error('该部门已存在');
            }
            $data['create_time'] = time();
            $data['update_time'] = time();
            $data['add_parentname'] = session('username');
            $re = Db::name('section')->insert($data);
            $log = [
                'content'=>'添加部门'.$data['title']
            ];
            $wed = new Weblog();
            $wed->insert($log);
            if(!$re){
                $this->error('添加失败');
            }
            session('list','');
            $this->success("添加成功",'manage');

        }

        $list = $this->showCate();
        $this->assign('section',$list);
        return $this->fetch('sectionForm');

    }

    /**
     * 部门编辑
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function sectionEdit(){

        $section_id = (int)input('section_id');
        if (request()->isAjax()) {

            $data = input('post.');
            $user = Db::name('section')->where(['title'=>$data['title']])->find();
            if($user){
                $this->error('该部门已存在');
            }
            $data['update_time'] = time();
            $data['add_parentname'] = session('username');
            $re = Db::name('section')->update($data);
            $log = [
                'content'=>'编辑部门'.$data['title']
            ];
            $wed = new Weblog();
            $wed->insert($log);
            if(!$re){
                $this->error('编辑失败');
            }
            session('list','');
            $this->success("编辑成功",'manage');

        }

        $section_data = Db::name('section')->where('section_id',$section_id)->find();

        $this->assign('info',json_encode($section_data,true));

        return $this->fetch('sectionEdit');

    }

    /**删除部门
     * URL：admin/section/sectionDel
     * @throws
     * @return array
     */
    public function sectionDel(){

        $section_id = input('post.section_id');

        if (session('aid')==1){

            Db::name('section')->where('section_id', $section_id)->update(['is_del' => 1,'update_time'=>time()]);

            $title = Db::name('section')->where('section_id', $section_id)->value('title');

            $log = [
                'content'=>'删除部门'.$title
            ];
            $wed = new Weblog();
            $wed->insert($log);
            session('list','');
            return $result = ['code'=>1,'msg'=>'删除成功!'];

        }else{

            return $result = ['code'=>0,'msg'=>'您没有删除部门的权限!'];

        }
    }

}